package com.pine.dbant.plugin.mysql.function;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.model.JdbcMetadataTreeView;
import com.pine.dbant.common.plugin.meta.*;
import com.pine.sunflower.core.utils.Strings;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xiaoyuan
 * @create 2022/12/27 14:54
 **/
@Slf4j
public class MysqlQueryFunctionsFunction extends AbstractQueryMetadataFunction<JdbcMetadataAnalysisConfig, List> {

    public MysqlQueryFunctionsFunction(String type) {
        super(type);
    }

    @Override
    public List<MetadataNode> doQuery(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        String catalog = queryMetadataParam.getConfiguration().getNecessaryValue("catalog");
        String sql = Strings.format("SELECT * FROM information_schema.ROUTINES WHERE routine_schema='{}'   ", catalog);
        List<Map<String, Object>> result = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(sql);
        List<MetadataNode> metadataNodes = new ArrayList<>();
        result.forEach(map -> {
            String functionName = String.valueOf(map.get("ROUTINE_NAME"));
            map.put("PARAMETERS", JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(
                    Strings.format("SELECT * FROM information_schema.PARAMETERS where specific_schema='{}' " +
                            "and specific_name='{}'",catalog, functionName)));
            metadataNodes.add(new DefaultMetadataNode()
                    .setName(functionName)
                    .setId(Strings.format("{}_{}_{}",metadataAnalysisConfig.getConnectionInfo().getId(),catalog,functionName))
                    .setType(JdbcMetadataTreeView.FUNCTION.getType())
                    .setLeaf(true)
                    .addProperties(map)
                    .addProperty(CONN_ID,metadataAnalysisConfig.getConnectionInfo().getId())
                    .addProperty(CATALOG,catalog));
        });
        return metadataNodes;
    }
}
